React 基礎:Function component vs Class component


什麼是 Class component

React 在 v16.8 之前主要是用 Class component;之後就都使用 Function component。v16.8 之前的 Function component 不能有 state,也沒有 hooks 的概念;但在之後 hooks 出現之後,局勢大變,大家就開始使用 Function component。

  • 來寫寫看 Class component
    最基本的寫法,只有 render
// function component 寫法
function Button( {onClick, children }) {
    console.log("render button");
    return <button onClick={onClick}>{children}</button>
}

// class component 寫法
class Button extends React.Component {
    render() {
        const { onClick, children} = this.props;
        return <button onClick={onClick}>{children}</button>
    }
}
  • 再挑戰看看 Class component
    this 的值,是由你如何呼叫 function 來決定
    • 比較:
      onClick() vs this.props.onClick()
    • this 的值:
      undefined vs this.props
    • 如何解決:
      • 使用建構子
      • 改成箭頭函式

@ TodoItem.js

export default class TodoItemC extends React.Component {
    // 使用建構子
    constructor(props) {
        super(props)

        // 設置 state
        this.state = {
            counter: 1
        }

        this.handleToggleClick = this.handleToggleClick.bind(this);
        this.handleDeleteClick = this.handleDeleteClick.bind(this);
    }

    // 或是改成 箭頭函式
    handleToggleClick() = () => {
        const { handleToggleIsDone, todo} = this.props
        handleToggleIsDone(todo.id)

        this.setState ({
            counter: this.state.counter + 1
        })
    }

    handleDeleteClick() = () => {
        const { handleDeleteTodo, todo } = this.props
        handleDeleteTodo(todo.id)
    }
    render() {
        const {
            className,
            size,
            todo,
            handleDeleteTodo,
            handleToggleIsDone,
        } = this.props;
      return (
           <TodoButtonWrapper>
               <Button onClick={handleToggleClick}>
                   {todo.isDone && "未完成"}
                   {!todo.isDone && "已完成"}
               </Button>
               <RedButton onClick={handleDeleteClick}>刪除</RedButton>
           </TodoButtonWrapper>
      )
    }
}

Class component 的生命週期(lifecycle)

圖片來源

  • 來寫個 Counter.js
import React from "react"

// props 裡面的屬性有變動的話,才會執行 shouldComponentUpdate()
export default class Counter extends React.PureComponent {
    constructor(props) {
        super(props)
        this.state = {
          counter: 1
        }
        console.log("constructor")
    }

    // lifecycle

    shouldComponentUpdate(nextProps, nextUpdate) {
        if (nextState.counter > 5) return false
        return true
    }
    componentDidMount() {
        console.log("did mount", this.state)
    }

    componentDidUpdate(prevprops, prevstate) {
        console.log("prevstate", prevState)
        console.log("update")
    }

    componentWillUnmount() {
        console.log("unmount")
    }

     // 

    handleClick = () => {
        this.setState({
            counter: this.state.counter + 1
        })
    }

    render() {
        const { counter } = this.state
        console.log("render")
        return (
            <div>
                <button onClick={this.handleClick}>+1</button>
                counter: {counter}
            </div>
        ) 
    }
}

結語

在 class component 階段,關注的是生命週期(lifecycle),在某個生命週期階段要做什麼;進入 function component 與 hooks 階段,關注的是 function 重新 render 之後要做什麼?








你可能感興趣的文章

How to Launch an Amazon EC2 Instance

How to Launch an Amazon EC2 Instance

Two sum 題目檢討紀錄

Two sum 題目檢討紀錄

搭配Windows工作排程, 讓Python自動執行

搭配Windows工作排程, 讓Python自動執行






留言討論